<template>
  <div>
    <el-tag
      v-for="(tag,index) in note.tags"
      :key="index"
      closable
      :disable-transitions="false"
      @close="handleClose(tag,index)"
    >
      {{ tag.name }}
    </el-tag>
    <el-input
      v-if="addTagVisible"
      ref="saveTagInput"
      v-model="newTagValue"
      class="input-new-tag"
      size="small"
      @keyup.enter.native="handleNewTagConfirm"
      @blur="handleNewTagConfirm"
    />
    <el-button v-else type="info" class="button-new-tag" size="small" @click="showNewTag">+ 标签</el-button>
  </div>
</template>

<script>
export default {
  name: 'NewTags',
  props: {
    tags: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      newTagValue: ''
    }
  },
  methods: {
    handleNewTagConfirm() {
      if (this.newTagValue) {
        if (!this.note.tags) {
          this.note.tags = []
        }
        this.note.tags.push({
          name: this.newTagValue
        })

        this.$emit('handleNewTagConfirm', this.tags)
      }
      this.addTagVisible = false
      this.newTagValue = ''
    },
    showNewTag() {
      this.addTagVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleClose(tag, index) {
      this.dynamicTags.splice(index, 1)
      this.$emit('handleNewTagConfirm', tag)
    }
  }
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
